#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "../help/aboutdialog.h"

#include "../thread/orderthread.h"

#include "../thread/chinactpquotethread.h"
//#include "../thread/chinactptraderthread.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 创建交易管理器
    /*
    ChinaCtpTraderThread *traderManager = new ChinaCtpTraderThread(this);

    // 启动行情（示例前置地址，需替换为实际地址）
    QString sfrontAddr = "tcp://182.254.243.31:30001"; // 上期所行情前置
    QString mBrokerID = "9999";
    QString mInventorID = "173380";
    QString mPassword = "exsJqm~!@#123";
    QString mAppID = "simnow_client_test";
    QString mAuthCode = "0000000000000000";
    traderManager->startMd(sfrontAddr,mBrokerID,mInventorID,mPassword,mAppID,mAuthCode);
    */

    //选中整行
    ui->orderTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    //自动根据内容调整宽度
    ui->orderTableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    // 创建右键菜单
    m_contextMenu = new QMenu(this);

    // 添加菜单项
    QAction *viewAction = new QAction("查看详情", this);
    QAction *editAction = new QAction("平仓", this);
    QAction *deleteAction = new QAction("删除", this);
    QAction *copyAction = new QAction("复制", this);

    // 添加分隔线
    m_contextMenu->addAction(viewAction);
    m_contextMenu->addAction(editAction);
    m_contextMenu->addSeparator();
    m_contextMenu->addAction(copyAction);
    m_contextMenu->addAction(deleteAction);


    // 连接菜单项信号
    connect(viewAction, &QAction::triggered, this, &MainWindow::onActionViewDetails);
    connect(editAction, &QAction::triggered, this, &MainWindow::onActionEditRow);
    connect(deleteAction, &QAction::triggered, this, &MainWindow::onActionDeleteRow);
    connect(copyAction, &QAction::triggered, this, &MainWindow::onActionCopyRow);

    // 连接表格点击信号
    connect(ui->orderTableWidget, &QTableWidget::itemClicked,
            this, &MainWindow::onTableItemClicked);

    // 允许右键弹出菜单
    ui->orderTableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->orderTableWidget, &QTableWidget::customContextMenuRequested,
            this, [=](const QPoint &pos) {
                // 获取右键点击位置对应的行
                QTableWidgetItem *item = ui->orderTableWidget->itemAt(pos);
                if (item) {
                    m_currentRow = item->row();
                    // 在点击位置显示菜单
                    m_contextMenu->exec(ui->orderTableWidget->mapToGlobal(pos));
                }
            });

    // 创建行情管理器
    ChinactpQuoteThread *mdManager = new ChinactpQuoteThread(this);
    connect(this, &QWidget::destroyed, this, [=]() {
        qDebug() << "窗体已销毁（彻底退出）";
        mdManager->stopMd();
        //traderManager->stopMd();
    });

    // 连接信号到UI处理
    connect(mdManager, &ChinactpQuoteThread::connected, this, [](){
        qDebug() << "主线程：行情服务器已连接";
    });
    connect(mdManager, &ChinactpQuoteThread::loginResult, this, [](bool success, const QString &msg){
        qDebug() << "主线程：" << msg;
    });
    connect(mdManager, &ChinactpQuoteThread::marketDataReceived, this,
        [=](const QString &instrumentID, double lastPrice, double askPrice, double bidPrice){
            // 在主线程更新UI（如表格、图表）
            //qDebug() << "主线程更新行情：" << instrumentID << "=" << lastPrice<< "=" << askPrice<< "=" << bidPrice;

            int rowCount = ui->orderTableWidget->rowCount();
            for (int row = 0; row < rowCount; ++row) {
                // 获取当前行的tradeID（在load时已存储到UserRole）
                QTableWidgetItem *idItem = ui->orderTableWidget->item(row, 4);
                if (!idItem) continue;

                if (idItem->text() == instrumentID) {
                    QTableWidgetItem *item = new QTableWidgetItem(QString::number(lastPrice,'2',2));
                    // 可添加样式变化（如闪烁提示）
                    item->setBackground(QColor(255, 255, 200)); // 浅黄色背景标识变动
                    ui->orderTableWidget->setItem(row, 8, item);
                    QTableWidgetItem *openPriceItem = ui->orderTableWidget->item(row, 5);
                    if (!openPriceItem) continue;
                    double openPrice = openPriceItem->text().toDouble();
                    openPrice = lastPrice-openPrice;
                    if (m_orderDataRow.contains(instrumentID)) {
                        openPrice = openPrice*m_orderDataRow[instrumentID];
                    }
                    QTableWidgetItem *profitItem = new QTableWidgetItem(QString::number(openPrice,'2',2));
                    // 可添加样式变化（如闪烁提示）
                    if(openPrice < 0){
                        profitItem->setForeground(QColor(69,139,0)); // 浅黄色背景标识变动
                    }else{
                        profitItem->setForeground(QColor(255, 0, 0)); // 浅黄色背景标识变动

                    }
                    //profitItem->setForeground(QColor(255,255,255));
                    profitItem->setTextAlignment(Qt::AlignRight);
                    QFont font = profitItem->font();
                    font.setPointSize(14);
                    profitItem->setFont(font);
                    ui->orderTableWidget->setItem(row, 10, profitItem);
                }
            }

        }
    );

    //connect(stopBtn, &QPushButton::clicked, mdManager, &ChinactpQuoteThread::stopMd);

    QStringList fieldOrder = {
        "tradeID","createdAt","style","quantity","symbol","price","stopLossPrice","stopProfitPrice","marketPrice","cost","profit"
    };

    QStringList quantityfieldOrder = {
        "quantity","price","stopLossPrice","stopProfitPrice","marketPrice","cost","profit"
    };

    // 创建线程实例
    OrderThread *thread = new OrderThread(this);

    // 连接线程信号到主线程的槽函数
    connect(thread, &OrderThread::progress, this, [=](int value) {
        qDebug() << "主线程接收进度：" << value << "%";
    });
    connect(thread, &OrderThread::resultReady, this, [=](const QVector<QMap<QString, QVariant>> &orderList) {
        qDebug() << "订单数据开始渲染1";
        ui->orderTableWidget->setRowCount(orderList.size());
        // 如果有数据，设置列数并获取字段名
        if (!orderList.isEmpty()) {
            qDebug() << "订单数据开始渲染2";
            // 获取所有字段名（假设第一行的键就是所有列名）
            QStringList fieldNames = orderList[0].keys();
            int columnCount = fieldNames.size();
            ui->orderTableWidget->setColumnCount(columnCount-1);
            // 循环添加数据到表格
            for (int row = 0; row < orderList.size(); ++row) {
                // 获取当前行的数据
                const QMap<QString, QVariant>& rowData = orderList[row];
                if(rowData.contains("weight") && rowData.contains("symbol")){
                    m_orderDataRow[rowData["symbol"].toString()] = rowData["weight"].toInt();
                }

                int col = 0;
                for (const QString& key : fieldOrder) {
                    // 判断map中是否存在该key（避免访问不存在的键）
                    QTableWidgetItem *item;
                    if (rowData.contains(key)) {
                        QVariant value = rowData[key]; // 根据key提取值
                        QString symbol = rowData["symbol"].toString();
                        if(m_symbols.indexOf(symbol) == -1){
                            m_symbols.append(symbol);
                        }
                        if(quantityfieldOrder.contains(key)){
                            item = new QTableWidgetItem(QString::number(value.toInt()/100, 'f', 2));
                        }else{
                            item = new QTableWidgetItem(value.toString());

                        }
                        // 可根据需要转换为具体类型（如int、QString等）
                        if (key == "profit") {
                            int profit = value.toInt();
                            if (profit > 0) {
                                item->setForeground(QColor(255, 0, 0)); // 红色文字
                            }
                        }
                    } else {
                        // 创建单元格并设置数据
                        item = new QTableWidgetItem("-");
                    }

                    // 添加到表格
                    ui->orderTableWidget->setItem(row, col, item);
                    col++;
                }
            }
            qDebug() << "订单数据渲染完成%";


            // 启动行情（示例前置地址，需替换为实际地址）
            QString frontAddr = "tcp://140.207.239.178:43174"; // 上期所行情前置



            mdManager->startMd(frontAddr,m_symbols);
        }
        thread->quit(); // 线程完成后退出
        thread->wait(); // 等待线程结束
    });

    // 设置线程参数
    thread->setParam(100);

    // 启动线程（会调用run()函数）
    thread->start();

    qDebug() << "主线程ID：" << QThread::currentThreadId();

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionabout_Bamboo_Tradeer_triggered()
{
    AboutDialog *aboutDialog = new AboutDialog();
    aboutDialog->setAttribute(Qt::WA_DeleteOnClose);  //关键设置
    aboutDialog->exec();

}
void MainWindow::onTableItemClicked(QTableWidgetItem *item)
{
    if (!item) return;

    m_currentRow = item->row();
    qDebug() << "选中了第" << m_currentRow << "行";
}

void MainWindow::onActionViewDetails()
{
    if (m_currentRow < 0 || m_currentRow >= ui->orderTableWidget->rowCount())
        return;

    QString id = ui->orderTableWidget->item(m_currentRow, 0)->text();
    QString name = ui->orderTableWidget->item(m_currentRow, 1)->text();
    QString status = ui->orderTableWidget->item(m_currentRow, 2)->text();

    QMessageBox::information(this, "详情",
                             QString("ID: %1\n名称: %2\n状态: %3").arg(id).arg(name).arg(status));
}

void MainWindow::onActionEditRow()
{
    if (m_currentRow < 0 || m_currentRow >= ui->orderTableWidget->rowCount())
        return;

    // 这里只是示例，实际应用中可以打开编辑对话框
    QMessageBox::information(this, "提示",
                             QString("开始编辑第%1行").arg(m_currentRow + 1));
}

void MainWindow::onActionDeleteRow()
{
    if (m_currentRow < 0 || m_currentRow >= ui->orderTableWidget->rowCount())
        return;

    if (QMessageBox::question(this, "确认",
                              QString("确定要删除第%1行吗？").arg(m_currentRow + 1)) == QMessageBox::Yes) {
        ui->orderTableWidget->removeRow(m_currentRow);
        m_currentRow = -1; // 重置选中行
    }
}

void MainWindow::onActionCopyRow()
{
    if (m_currentRow < 0 || m_currentRow >= ui->orderTableWidget->rowCount())
        return;

    // 获取当前行数据
    QString data;
    for (int col = 0; col < ui->orderTableWidget->columnCount(); ++col) {
        data += ui->orderTableWidget->item(m_currentRow, col)->text() + "\t";
    }

    // 复制到剪贴板
    //QClipboard *clipboard = QApplication::clipboard();
    //clipboard->setText(data);

    QMessageBox::information(this, "提示", "行数据已复制到剪贴板");
}

